package com.lkd.job;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class VmJob {
    @Autowired
    private VendingMachineService vendingMachineService;


    /**
     * 售货机服务定时扫描补货
     * @param param
     * @return
     */
    @XxlJob("scanAllVmAndReplenish")
    public ReturnT<String> scanAllVmAndReplenish(String param){
        //获取分片信息
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //总分片数
        int total = shardingVo.getTotal();
        //当前分片数
        int index = shardingVo.getIndex();
        //1.查询出当前分片下所有的运营中的售货机
        List<VendingMachineEntity> list = vendingMachineService.list(Wrappers
                .<VendingMachineEntity>lambdaQuery()
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id",total + ") =" + index));
        if (CollectionUtils.isEmpty(list)){
            return ReturnT.FAIL;
        }

        //2.循环检查每个售货机补货的数量
        for (VendingMachineEntity vendingMachine : list) {
            String innerCode = vendingMachine.getInnerCode();
            vendingMachineService.sendChannelStockout(innerCode);
        }

        return ReturnT.SUCCESS;
    }
}
